require('./pollyfill/index')
const {
  toast, confirm, showLoading, hideLoading, showAddressModal
} = require('./utils/util')

App({
  onLaunch: function () {
    showLoading()
    wx.login({
      success: res => {
        this.getOpenID(res.code)
      },
      fail: err => {
        hideLoading()
        this.dispatchError('登录失败，请检查网络连接')
      }
    })
  },
  appReady: false,
  appError: false,
  errMsg: '',
  readyCallback: null,
  errorCallback: null,
  globalData: {
    userWxInfo: null,
    userRole: "0",
    webUrl: "https://wx.withwheat.com",
    siloUrl: "https://silo.withwheat.com",
    selectAddress: {
      status: -1,
      value: null
    },
    sexValues: ['女', '男', '保密'],
    sessionID: null,
    authToken: null,
    address: null,
    coupon: {
      status: -1,
      value: null
    },
    canReqSession: true,
    canReqAddress: true,
    canReqToken: true,
    needReqAfterUpdateAddress: false,
    needClearBreadCar: null,
    needClearCakeCar: null
  },
  isAuthrized: function () {
    return new Promise(resolve => {
      wx.getSetting({
        success: (res) => {
          if (res.authSetting["scope.userInfo"]) {
            resolve(true)
          } else {
            resolve(false)
          }
        },
        fail: () => {
          resolve(false)
        }
      })
    })
  },
  getUserWxInfo: function () {
    return new Promise((resolve, reject) => {
      if (this.globalData.userWxInfo) {
        resolve(this.globalData.userWxInfo)
      } else {
        wx.getUserInfo({
          success: (res) => {
            this.globalData.userWxInfo = res.userInfo
            let url = '/weappmall/user/userinfo'
            let params = {
              uname: "weappmall",
              openId: this.globalData.openID,
              encryptedData: res.encryptedData,
              iv: res.iv
            }
            this.request(url, params).then(res => {
              if (res.code === '0000') {
                this.globalData.unionID = res.data.unionId
                this.getSessionID()
                resolve(res.userInfo)
              } else {
                reject(res.message)
              }
            }).catch(() => {
              reject('获取用户失败')
            })
          },
          fail: () => {
            reject('授权失败')
          }
        })
      }
    })
  },
  getOpenID: function (js_code) {
    let url = '/weappmall/user/login'
    let params = {
      uname: "weappmall",
      js_code: js_code
    }
    this.request(url, params).then(res => {
      if (res.code === '0000') {
        console.log('openId: ' + res.data.openId)
        this.globalData.openID = res.data.openId
        if (res.data.unionId) {
          this.globalData.unionID = res.data.unionId
          this.getSessionID()
        } else {
          this.getUserWxInfo().catch(err => {
            this.isAuthrized().then(yes => {
              if (yes) {
                toast.error(err)
              } else {
                wx.navigateTo({
                  url: '/pages/auth/auth'
                })
              }
            })
          })
        }
      }
    }).catch(err => {
      hideLoading()
      this.dispatchError(err)
    })
  },
  request: function (url, params = {}, method = 'POST') {
    return new Promise((resolve, reject) => {
      let headers = {
        "Content-Type": "application/x-www-form-urlencoded"
      }
      if (this.globalData.sessionID) {
        headers.__sessionid = this.globalData.sessionID
      }
      let baseUrl = ''
      if (/\.json$/.test(url)) {
        baseUrl = this.globalData.siloUrl
        headers["Content-Type"] = "application/json"
      } else {
        baseUrl = this.globalData.webUrl
      }
      wx.request({
        url: baseUrl + url,
        header: headers,
        method: method.toUpperCase(),
        data: params,
        success: res => {
          if (res.statusCode === 200) {
            resolve(res.data)
          } else {
            if (typeof res.data === 'object') {
              const errMsg = res.data.error || res.data.errMsg
                || res.data.errmsg || res.data.MSG || res.data.msg
                || res.data.message || '未知错误'
              reject(errMsg, res.statusCode, res.data)
            } else {
              reject(`请求发生异常, stauts:${res.statusCode}`)
            }
          }
        },
        fail: err => {
          reject('请检查网络连接')
        }
      })
    })
  },
  get: function (url, params) {
    return this.request(url, params, 'GET')
  },
  getUserLocation: function () {
    wx.getLocation({
      success: (res) => {
        this.showAddress(res.latitude, res.longitude)
      }
    })
  },
  getSessionAgain: function () {
    this.globalData.canReqSession = true
    this.getSessionID()
  },
  getSessionID: function () {
    if (this.globalData.sessionID != null) {
      return
    }
    if (this.globalData.canReqSession === false) {
      return
    }
    this.globalData.canReqSession = false
    let params = {
      uname: "weappmall",
      openId: this.globalData.openID,
      unionId: this.globalData.unionID
    }
    this.request('/weappmall/user/getSession', params).then(res => {
      if (res.code !== '0000') {
        return
      }
      this.globalData.sessionID = res.data.SESSIONID
      Promise.all([
        this.getAddress(),
        this.getUserInfo(),
        this.getUserToken()
      ]).then(values => {
        hideLoading()
        this.dispatchReady()
      })
    })
  },
  getUserInfo: function () {
    if (!this.globalData.sessionID) {
      return Promise.resolve()
    }
    let url = '/yuanmai_we/usercenter/user/info'
    let params = {
      uname: 'zaofans',
      __sessionid: this.globalData.sessionID
    }
    return this.get(url, params).then(res => {
      this.globalData.userid = res.ID
      this.globalData.couponCount = res.COUPONS
      this.globalData.balance = res.BALANCE
      this.globalData.cardNO = res.CARDNO
      this.globalData.isPwd = res.ISPWD
      this.globalData.personInfo = {
        USERNAME: res.USERNAME,
        USERSEX: res.USERSEX,
        MOBILE: res.MOBILE,
        USERBIRTHDAY: res.USERBIRTHDAY
      }
      return res
    })
  },
  getAddress: function () {
    if (this.globalData.sessionID == null) {
      this.getSessionID()
      return Promise.resolve()
    }
    if (this.globalData.canReqAddress === false) {
      return Promise.resolve()
    }
    this.globalData.canReqAddress = false
    let url = '/yuanmai_we/usercenter/address/default'
    return this.get(url).then(res => {
      if (!res.ADDRESS) {
        this.globalData.address = null
        return
      }
      this.globalData.needReqAfterUpdateAddress = true
      this.globalData.address = res
    })
  },
  getUserToken: function () {
    if (this.globalData.authToken != null) {
      let curstamp = (new Date()).getTime()
      if (this.globalData.expireAt >= curstamp) {
        return Promise.resolve()
      }
    } else {
      if (this.globalData.sessionID == null) {
        this.getSessionID()
        return Promise.resolve()
      }
    }
    if (this.globalData.canReqToken === false) {
      return Promise.resolve()
    }
    this.globalData.canReqToken = false
    let url = '/yuanmai_we/silo/user/auth/create'
    return this.request(url).then(res => {
      this.globalData.authToken = res.authToken
      this.globalData.expireAt = res.expireAt
      console.log('authToken: ' + res.authToken)
    })
  },
  getVipInfo: function (reload = false) {
    if (!this.globalData.authToken) {
      return Promise.resolve()
    }
    if (!reload && this.globalData.vipInfo) {
      return Promise.resolve(this.globalData.vipInfo)
    }
    let url = '/silo/h5/2201.json'
    let params = {
      auth: this.globalData.authToken
    }
    return this.request(url, params).then(res => {
      this.globalData.vipInfo = res.data
      return res.data
    })
  },
  tokenIsValid: function () {
    if (this.globalData.authToken != null) {
      let curstamp = (new Date()).getTime()
      if (this.globalData.expireAt >= curstamp) {
        return true
      } else {
        return false
      }
    } else {
      return false
    }
  },
  getPrevPage: function() {
    const pages = getCurrentPages()
    return pages[pages.length - 2]
  },
  toast: toast,
  confirm: confirm,
  showLoading: showLoading,
  hideLoading: hideLoading,
  showAddressModal: showAddressModal,
  ready: function (callback) {
    this.readyCallback = callback
    if (this.appReady) {
      this.dispatchReady()
    }
  },
  error: function (callback) {
    this.errorCallback = callback
    if (this.appError) {
      this.dispatchError()
    }
  },
  dispatchReady: function () {
    this.appReady = true
    if (typeof this.readyCallback === 'function') {
      this.readyCallback.apply(this, arguments)
      this.readyCallback = null
    }
  },
  dispatchError: function () {
    this.appError = true
    this.errMsg = arguments.length > 0
      ? [].slice.call(arguments)
      : this.errMsg
    if (typeof this.errorCallback === 'function') {
      this.errorCallback.apply(this, this.errMsg)
      this.errorCallback = null
    }
  }
})
